package com.storage.mongo;

import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.storage.mongo.EComments;
import com.storage.mongo.ETopic;
import com.wink.charity.Charity;
import com.wink.common.Identity;
import com.wink.subscribe.MongoSub;
import com.wink.subscribe.Subscription;

public class CharityDB {

	private Morphia morp;
	private Mongo m; 
	private Datastore ds;
	
	
	public CharityDB() throws UnknownHostException, MongoException {

		morp = new Morphia();
		m = new Mongo( "localhost" , 27017 );
		//drop db
		//m.dropDatabase("mydb");
		System.out.println("The quick brown fox");
		morp.map(MongoCharity.class);
		System.out.println("jumped over the fence");
		ds = morp.createDatastore("mydb");
	}

	public void addCharity(Charity charity) {
		MongoCharity mCharity = new MongoCharity();
		MongoIdentity mIdentity = new MongoIdentity();
		
		if(charity.getAmount() != null) {
			mCharity.setAmount(charity.getAmount());
		}
		
		if(charity.getName() != null) {
			mCharity.setName(charity.getName());
		}
		
		if(charity.getCharityCommunityID() != null) {
			mCharity.setCharityCommunityID(charity.getCharityCommunityID());
		}
		
		if(charity.getDescription() != null) {
			mCharity.setDescription(charity.getDescription());
		}
		
//		if(charity.getIdentity() != null) {
//			Identity identity = charity.getIdentity();
//			
//			if(identity.getFromUser() != null) {
//				mIdentity.setFromUser(identity.getFromUser());
//			}
//			
//			if(identity.getFromCommunity() != null) {
//				mIdentity.setFromCommunity(identity.getFromCommunity());
//			}
//			
//			if(identity.getDate() != null) {
//				mIdentity.setDate(identity.getDate().toString());
//			}
//		}
//		
		mCharity.setIdentity(mIdentity);
		
		ds.save(mCharity);
		System.out.println("Charity created successfully");
	}
	
	public ArrayList<Charity> getAllCharities() throws ParseException {
		ArrayList<Charity> charityList = new ArrayList<Charity>();
		
		List<MongoCharity> list = ds.find(MongoCharity.class).asList();

		for(MongoCharity m: list) {
			charityList.add(m.toCharity());
		}

		return charityList;
	}
	
}